package com.tjyx.common;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tjyx.common.util.DispatcherUtil;

/**
 * 转发控制器，系统所有的请求路径都经过此类进行转发，实现简单的MVC
 * @author zhutianjie
 *
 */
public class DispatcherServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String ROOT_PATH = "webRootPath";
	private static final DispatcherUtil DISPATCHER_UTIL = new DispatcherUtil();
	private static Map<String, String> requestConfigMap;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String requestURI = request.getRequestURI();
		try {
			requestConfigMap = DISPATCHER_UTIL
					.checkOutRequestConfig(requestURI);
		} catch (DispatcherException e) {
			e.printStackTrace();
		}
		Class actionServlet = null;
		try {
			actionServlet = Class.forName(requestConfigMap.get(DispatcherUtil.ACTION_NAME));
			Method actionMethod = actionServlet.getMethod(requestConfigMap.get(DispatcherUtil.ACTION_METHOD),
					HttpServletRequest.class, HttpServletResponse.class);
			String result = (String) actionMethod.invoke(actionServlet.newInstance(), request, response);
			if(result!=null){
				if(result.equals("NoResult")){
					return;
				}
				if(requestConfigMap.get(DispatcherUtil.FORWARD_METHOD).equals("redirect")) {
					response.sendRedirect(result);
				} else {
					RequestDispatcher dispatcher = request.getRequestDispatcher(result);
					dispatcher.forward(request, response);
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	@Override
	public void init() throws ServletException {
		getServletContext().setAttribute(ROOT_PATH, getServletContext().getContextPath());
	}

}
